﻿using System;
using System.Data;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using Service;
using Resources;

public partial class workOrderView : Page
{
    DataTable workOrderList  = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        txtHiddenworkOrderId.Text = Request.QueryString["workOrderId"];
        Session["whereClause"] = null;
        if (Session["whereClause"] == null)
            Session["whereClause"] = GetWhereClause();

        
        if (Session["orderByClause"] == null)
            Session["orderByClause"] = txthiddenOrderbyClause.Text;

        new Utility().SetRowToDisplay(grdEquipment, Session["rowsToSDisplay"]);

        if (!IsPostBack)
        {

            Session["workOrderId"] = Request.QueryString["workOrderId"];
            Session["defaultTabIndex"] = Request.QueryString["tabIndex"];
            if (Request.QueryString["authorize"] != null)
            {
                if (!new Utility().TestPermissions(Resource.PermissionAuthorizeWorkOrder))
                {
                    lblMessageValidate.Text = Resource.Permission;
                    return;
                }
                int workOrderId = Request.QueryString["workOrderId"] != null ? Int32.Parse(Request.QueryString["workOrderId"]) : 0;
                new WorkOrderService().SetAuthorizeWorkOrder(workOrderId);
                txtHiddenWhereClause.Text = Session["whereClause"].ToString();
                txthiddenOrderbyClause.Text = Session["orderByClause"].ToString();
                

            }else 
            
             txtHiddenWhereClause.Text = Session["whereClause"].ToString();
             txthiddenOrderbyClause.Text = Session["orderByClause"].ToString();
               
           
            if (Session["pageIndex"] != null)
            
                grdEquipment.PageIndex = Int32.Parse(Session["pageIndex"].ToString());

            
            
            if ((Request.QueryString["delete"] != null))
            {
                if (!new Utility().TestPermissions(Resource.PermissionDeleteWorkOrder))
                {
                    lblMessageValidate.Text = Resource.Permission;
                    return;
                }
                try
                {
                    
                    Session["workOrderId"] = null; // to hide panel in detail tab
                    DeleteWorkOrder(new Utility().ConvertToInteger(Session["workOrderId"]));
                    
                }catch(Exception ex)
                {
                    
                    lblMessageValidate.Text = Resource.MsgDeleteWorkOrderFail;
                }

            }
            
            txtHiddenPageIndex.Text = "0";
        }
        else txtHiddenPageIndex.Text = "0";
        grdEquipment.PageIndex = !String.IsNullOrEmpty(txtHiddenPageIndex.Text) ? Int32.Parse(txtHiddenPageIndex.Text) : 0;
    }
   
    public bool GetAuthorize()
    {
       return chkAuthorized.Checked;
    }
    public string GetTaskId()
    {
        string taskString = string.Empty;
        if (Request.QueryString["taskId"] != null)
            taskString = "&taskId="+Request.QueryString["taskId"];
        return taskString;
        
    }
    protected void grdEquipment_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdEquipment.PageIndex = e.NewPageIndex;
        txtHiddenPageIndex.Text = grdEquipment.PageIndex.ToString();

        Session["pageIndex"] = grdEquipment.PageIndex;
        Session["defaultTabIndex"] = 0;
        Session["workOrderId"] = null;

    }
    protected void grdEquipment_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {

    }
    protected void grdEquipment_SelectedIndexChanged(object sender, EventArgs e)
    {
        
        
    }
    protected void grdEquipment_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
       
            
    }
    public int GetPageIndex()
    {
        return Session["pageIndex"] != null
                   ?Int32.Parse(Session["pageIndex"].ToString()): 0;
    }
    public int GetTabIndex()
    {
        int tabIndex = Request.QueryString["tabIndex"] != null
                        ?
                            Int32.Parse(Request.QueryString["tabIndex"])
                        : 0;
        if (Session["defaultTabIndex"] != null)
        {
            tabIndex = Int32.Parse(Session["defaultTabIndex"].ToString());
            Session["defaultTabIndex"] = null;
        }

        return tabIndex;
    }
    public string GetDisplayMode()
    {
        return Request.QueryString["detail"];
    }
    protected void btnValidate_Click(object sender, EventArgs e)
    {
        if (!new Utility().TestPermissions(Resource.PermissionViewWorkOrder))
        {
            lblMessageValidate.Text = Resource.Permission;
            lblTotalEquipment.Visible = false;
            grdTemporary.Visible = false;
            return;
        }
       
        lblMessageValidate.Visible = false;
        
        Session["whereClause"] = GetWhereClause();
        txtHiddenWhereClause.Text = GetWhereClause();
        Session["defaultTabIndex"] = 0;

        // empty textboxes after searched clicked
        txtRequestDate.Text = string.Empty;
        txtRequiredDate.Text = string.Empty;
       

    }
   
    protected string GetWhereClause()
    {
        string whereClause = " WHERE ";
        string and = "";
        string str = "";
        if (drlEmployee.SelectedIndex > 0)
        {
            str += and + " (Employee.EmployeeId =" + this.drlEmployee.SelectedValue + ")";
            and = " and ";
        }

        if (drlCriteria.SelectedIndex > 0)
        {
            str += and + " (CRITERIA.CRITERIAID=" + drlCriteria.SelectedValue + ")";
            and = " and ";
        }

        if (drlRequestType.SelectedIndex > 0)
        {
            str += and + " (REQUESTMADEBY.REQUESTMADEBYID=" + this.drlRequestType.SelectedValue + ")";
            and = " and ";
        }
        if (txtRequestDate.Text != string.Empty)
        {

            str += and + "( WORKORDER.DATEREQUEST=convert(datetime,'" + txtRequestDate.Text + "', 101) )";
            and = " and ";

        }
        if (txtRequiredDate.Text != string.Empty)
        {

            str += and + "( TASKINWORKORDER.DATEREQUIRED=convert(datetime,'" + txtRequiredDate.Text + "', 101) )";
            and = " and ";

        }
        if (drlStatus.SelectedIndex > 0)
        {
            str += and + " (WORKORDER.StatusId=" + this.drlStatus.SelectedValue + ")";
            and = " and ";
        }

        if (chkAuthorized.Checked && !chkNewWO.Checked)
        {
            str += and + "( WORKORDER.AUTHORISE = 1)";
        }

        else if (!chkAuthorized.Checked && chkNewWO.Checked)
        {

                str += and + "( WORKORDER.AUTHORISE = 0 )";
                and = " and ";
        }
        else if (chkAuthorized.Checked && chkNewWO.Checked)
        {

            str += and + "( WORKORDER.AUTHORISE = 0 or WORKORDER.AUTHORISE = 1 )";
            and = " and ";
        }
        
        
        if (!String.IsNullOrEmpty(str))
            whereClause = " and " + str + " ";
        else
            whereClause = " WHERE WORKORDER.WorkOrderId  = 0  ";


       
        return whereClause;
    }
    
    private void DisableRequiredDate(bool enabled)
    {
        txtRequiredDate.Enabled = enabled;
        imgRequiredDate.Enabled = enabled;
    }

    protected void odsSparepart_Selected(object sender, ObjectDataSourceStatusEventArgs e)
    {
        
        if (chkAuthorized.Checked)
            lblTotalEquipment.Text = "Total Work order already assigned : " +(e.ReturnValue != null ? ((DataTable)e.ReturnValue).Rows.Count.ToString() :0.ToString());
        else
            lblTotalEquipment.Text = "Total Unauthorized Work order  : " +( e.ReturnValue != null ? ((DataTable)e.ReturnValue).Rows.Count.ToString() : 0.ToString());
           
        grdTemporary.Visible = e.ReturnValue != null ? (((DataTable)e.ReturnValue).Rows.Count == 0 ? true : false) : true;    
        
    }
    protected void grdEquipment_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Select"))
        {
            int workOrderId = Convert.ToInt32(grdEquipment.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
           
            Session["workOrderId"] = workOrderId;
            Session["defaultTabIndex"] = 1 ;
            Session["rowSelectedIndex"] = Convert.ToInt32(e.CommandArgument);
        }
        new Utility().SetSelectedColorToGridView(e, grdEquipment);
        
        
    }
    private void DeleteWorkOrder(int workOrderId)
    {
        WorkOrderService _WorkOrderService= new WorkOrderService();
        _WorkOrderService.DeleteTasksInWorkOrder(workOrderId);
        _WorkOrderService.DeleteWorkOrder(workOrderId);

    }
    
}
